package com.cgy.utils.spider.adaptor;

import com.cgy.utils.spider.callback.AbstractCallBack;
import com.cgy.utils.spider.config.AbstractConfig;
import com.cgy.utils.spider.config.WebMagicConfig;
import com.cgy.utils.spider.handler.WebMagicProcessor;

import us.codecraft.webmagic.Spider;

/**
 * webmagic适配器
 * @author CH
 *
 */
public class WebMagicAdaptor extends AbstractAdaptor{

	protected AbstractCallBack abstractCallBack;
	protected WebMagicProcessor webMagicProcessor;
	private Spider spider;
	
	public WebMagicAdaptor() {
		this.webMagicProcessor = WebMagicProcessor.create();
	}
	
	@Override
	public void run(String... url) {
		this.spider.addUrl(url).run();
	}

	@Override
	public void runAsync(String... url) {
		this.spider.addUrl(url).runAsync();
	}

	@Override
	public void stop() {
		if(null != this.spider) {
			this.spider.stop();
		}
	}

	@Override
	public AbstractAdaptor callback(AbstractCallBack abstractCallBack) {
		this.abstractCallBack = abstractCallBack;
		return this;
	}


	@Override
	public AbstractAdaptor setConfig(AbstractConfig config) {
		if(config instanceof WebMagicConfig) {
			WebMagicConfig webMagicConfig = (WebMagicConfig) config;
			
			webMagicProcessor.setSite(webMagicConfig.getSite());
			webMagicProcessor.setElements(config.getElements());
			webMagicProcessor.setResolver(config.getResolver());
			webMagicProcessor.setCallBack(webMagicConfig.getCallback());
			
			this.spider = Spider.create(webMagicProcessor);

			if(0 != webMagicConfig.getThread()) {
				this.spider.thread(webMagicConfig.getThread());
			}
			if(null != webMagicConfig.getDownloader()) {
				this.spider.setDownloader(webMagicConfig.getDownloader());
			}
		}
		return this;
	}
	/**
	 * 初始化
	 */
	public static WebMagicAdaptor create() {
		return new WebMagicAdaptor();
	}

}
